package com.mia.craftstudio.minecraft;

import com.mia.craftstudio.libgdx.Matrix4;
import com.mia.craftstudio.libgdx.Vector3;
import java.nio.FloatBuffer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;

public class ProjectionHelper {
   public static Matrix4 getOrthoMatrix() {
      Minecraft mc = Minecraft.getMinecraft();
      ScaledResolution rez = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
      float left = 0.0F;
      float right = (float)rez.getScaledWidth();
      float bottom = (float)rez.getScaledHeight();
      float top = 0.0F;
      float near = 1000.0F;
      float far = 3000.0F;
      float tx = -(right + 0.0F) / (right - 0.0F);
      float ty = -(0.0F + bottom) / (0.0F - bottom);
      float tz = -2.0F;
      Matrix4 ortho = new Matrix4();
      ortho.val[0] = 2.0F / (right - 0.0F);
      ortho.val[5] = 2.0F / (0.0F - bottom);
      ortho.val[10] = -0.001F;
      ortho.val[15] = 1.0F;
      ortho.val[12] = tx;
      ortho.val[13] = ty;
      ortho.val[14] = -2.0F;
      return ortho;
   }

   public static Vector3[] getExtend(Vector3[] vertices) {
      float xMin = Float.MAX_VALUE;
      float yMin = Float.MAX_VALUE;
      float zMin = Float.MAX_VALUE;
      float xMax = -3.4028235E38F;
      float yMax = -3.4028235E38F;
      float zMax = -3.4028235E38F;

      for(int i = 0; i < 8; ++i) {
         xMin = Math.min(xMin, vertices[i].x);
         yMin = Math.min(yMin, vertices[i].y);
         zMin = Math.min(zMin, vertices[i].z);
         xMax = Math.max(xMax, vertices[i].x);
         yMax = Math.max(yMax, vertices[i].y);
         zMax = Math.max(zMax, vertices[i].z);
      }

      Vector3[] extend = new Vector3[]{new Vector3(xMin, yMin, zMin), new Vector3(xMax, yMax, zMax)};
      return extend;
   }

   public static void printMatrix(int glMatrix) {
      FloatBuffer projmat = BufferUtils.createFloatBuffer(16);
      GL11.glGetFloat(glMatrix, projmat);

      for(int i = 0; i < 4; ++i) {
         System.out.printf("%16.10f ", projmat.get(i));
         System.out.printf("%16.10f ", projmat.get(i + 4));
         System.out.printf("%16.10f ", projmat.get(i + 8));
         System.out.printf("%16.10f ", projmat.get(i + 12));
         System.out.printf("\n");
      }

      System.out.printf("======\n");
   }

   public static Matrix4 getMatrix(int glMatrix) {
      FloatBuffer projmat = BufferUtils.createFloatBuffer(16);
      GL11.glGetFloat(glMatrix, projmat);
      Matrix4 retmat = new Matrix4();

      for(int i = 0; i < 16; ++i) {
         retmat.val[i] = projmat.get();
      }

      return retmat;
   }
}
